package com.framework.bdf4j.sysadm.service.impl;

import com.framework.bdf4j.comm.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.sysadm.entity.SysUser;
import com.framework.bdf4j.sysadm.service.SysUserService;
import com.framework.bdf4j.sysadm.vo.SecurityUser;
import com.framework.bdf4j.sysadm.vo.UserInfo;

/**
 * <b>文件名： </b>MyUserDetailsService.java<br/>
 * <b>类描述： </b>自定义Spring Security登录查询类<br/>
 */
public class MyUserDetailsService implements UserDetailsService{

    @Autowired
	private SysUserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${login.retryNumber}")
    private String retryNumber;
	
	@Override
    public UserDetails loadUserByUsername(String userName) throws AuthenticationException {
		
	    SysUser authentication = userService.getOne(new QueryWrapper<SysUser>().eq("loginname", userName).eq("del_flag", Constants.STATUS_NORMAL)); 

        if (authentication == null) {
            // throw new UsernameNotFoundException("用户 " + userName + " 不存在");
            redisUtils.setLoginRedis(userName);
            Integer value = redisUtils.getValue(userName);
            throw new UsernameNotFoundException("用户名或者密码错误，您还剩下 " + (Integer.parseInt(retryNumber) - value) + " 次机会");
        }

        if(!Constants.STATUS_NORMAL.equals(authentication.getLockFlag()))
        {
        	throw new DisabledException("用户 " + userName + " 被禁用");
        }
        
        UserInfo userinfo = userService.findUserInfo(authentication); 
        return new SecurityUser(authentication,userinfo);
    }
}
